﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Library
{
    class DalChiTietKho
    {

        internal static int GetLastestSoLuong(int ID_SP)
        {
            List<ChiTietKho> result = new List<ChiTietKho>();

            QLDCTTEntities da = new QLDCTTEntities();

            try
            {
                result = (from ctk in da.ChiTietKho
                         where ctk.ID_SP == ID_SP && ctk.Ngay < DateTime.Now
                         orderby ctk.Ngay descending
                         select ctk).ToList();
                
                if (result.Count > 0)
                    result.Last();
            }

            catch (Exception ex)
            {
                throw ex;
            }
            if (result.Count == 0)
                return 0;

            return result[0].SoLuongTon;
        }

        internal static void Add(int ID_SP, int SoLuong)
        {
            try
            {
                ChiTietKho ctk = new ChiTietKho();

                ctk.ID_SP = ID_SP;
                ctk.Ngay = DateTime.Now;
                ctk.SoLuongTon = GetLastestSoLuong(ID_SP) + SoLuong;

                QLDCTTEntities entities = new QLDCTTEntities();
                entities.ChiTietKho.Add(ctk);

                entities.SaveChanges();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        internal static void Sub(int ID_SP, int SoLuong)
        {
            try
            {
                ChiTietKho ctk = new ChiTietKho();

                ctk.ID_SP = ID_SP;
                ctk.Ngay = DateTime.Now;
                ctk.SoLuongTon = GetLastestSoLuong(ID_SP) - SoLuong;

                QLDCTTEntities entities = new QLDCTTEntities();
                entities.ChiTietKho.Add(ctk);

                entities.SaveChanges();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
